package com.st.controller;


import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.st.base.BaseResult;
import com.st.po.UserLoginPo;
import com.st.pojo.Token;
import com.st.pojo.User;
import com.st.security.SecurityDetailsImpl;
import com.st.service.TokenService;
import com.st.service.UserService;
import com.st.utils.JWTUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.print.DocFlavor;
import java.util.HashMap;
import java.util.Objects;

@Tag(name = "user",description = "用户表的各种操作")
@RestController
@RequestMapping(path = "user")
public class UserController {


    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private JWTUtil jwtUtil;

    @RequestMapping(path = "login",method = RequestMethod.POST)
    @Operation(summary = "用户登录",description = "登录成功颁发token")
    public BaseResult login(@RequestBody UserLoginPo userLoginPo){
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(userLoginPo.getName(),userLoginPo.getPass());

        Authentication authentication = authenticationManager.authenticate(token);
        
        if (Objects.nonNull(authentication)){
            SecurityDetailsImpl principal = (SecurityDetailsImpl) authentication.getPrincipal();
            User user = principal.getUser();

            QueryWrapper<Token> qw = new QueryWrapper<>();
            QueryWrapper<Token> eq = qw.eq(Token.COL_U_ID, user.getId());
            Token one = tokenService.getOne(eq);
            if (one != null){
                HashMap<String, String> stringToken = jwtUtil.cerateToken(user.getId());
                return BaseResult.ok(stringToken);
            }else {
                tokenService.save(new Token(user.getId(), JSON.toJSONString(authentication)));
                //认证通过,颁发业务token
                HashMap<String, String> stringToken = jwtUtil.cerateToken(user.getId());
                return BaseResult.ok(stringToken);
            }
        }

        return BaseResult.error("认证失败");
    }

}
